package ru.arriah.servicedesk.web.leadExecutor.action;

import java.io.IOException;
import java.util.Collection;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.TaskBean;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;
import ru.arriah.servicedesk.web.commonaction.exception.PrivilegesException;

public class DisplayExecutorsListAction extends DumbAction {
   protected RequestManagerLocalHome requestManagerHome;

   public DisplayExecutorsListAction () throws NamingException {
      super();

      requestManagerHome =
         Utils.getRequestManagerHomeInterface();
   }
   
   
   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {
        int leadExecutorId = Utils.getUserId(request);
        int requestId = idVal(request.getParameter("request_id"));
        
        String orderBy = request.getParameter("orderBy");
        String order = request.getParameter("order");
        order = (order == null) ? "" : order;
        orderBy = (orderBy == null) ? "" : orderBy;
        
        RequestManagerLocalObject requestManager = 
          requestManagerHome.create();
        
        RequestBean requestBean = 
          requestManager.selectRequest(requestId);
        
        if (requestBean.getLeadExecutorId()!=leadExecutorId)
          throw new PrivilegesException();
        
        Collection<TaskBean> tasksList = 
          requestManager.selectTasksByRequest(
            requestId,
            orderBy,
            order
          );        
        
        requestManager.remove();

        request.setAttribute("tasksList", tasksList);
        request.setAttribute("requestBean", requestBean);
        request.setAttribute(
          "order", 
          (order.equals("ASC")) ? "DESC" : "ASC"
         );
        
        return actionMapping.getSuccessTarget();
      } catch (Exception e) {
         handleException(e, "execute");
         throw new InternalException("ErrorMessage.internal");
      }
   }
}